package com.drinks.yiniang.ui.widget.textview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.support.v7.widget.AppCompatTextView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.TypedValue;

import com.drinks.yiniang.R;
import com.hansen.library.utils.ColorUtils;
import com.hansen.library.utils.ScreenSizeUtils;
import com.hansen.library.utils.StringUtils;

/**
 * @author han
 * @date 2019/12/26
 */
public class TagTextView extends AppCompatTextView {

    private final int DEFAULT_COLOR;

    private int mTagColor;
    private int mTagRadius;

    private Paint mPaint;

    private RectF mRecF;

    public TagTextView(Context context) {
        this(context, null);
    }

    public TagTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public TagTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        DEFAULT_COLOR = ColorUtils.getColorById(getContext(), R.color.color_ef3024);

        init(attrs);
    }

    private void init(AttributeSet attrs) {
        mTagColor = DEFAULT_COLOR;
        mTagRadius = ScreenSizeUtils.dp2px(getContext(), 3);

        if(attrs != null) {
            TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.TagTextViewAttrs);

            mTagColor = a.getColor(R.styleable.TagTextViewAttrs_tagTextTagColor, DEFAULT_COLOR);

            mTagRadius = a.getDimensionPixelOffset(R.styleable.TagTextViewAttrs_tagTextTagRadius, mTagRadius);

            a.recycle();
        }

        mPaint = new Paint();

        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setColor(mTagColor);
        mPaint.setStrokeWidth(1);
        mPaint.setAntiAlias(true);

        mRecF = new RectF();

        int dp3 = ScreenSizeUtils.dp2px(getContext(), 3);
        int dp6 = ScreenSizeUtils.dp2px(getContext(), 6);

        setPadding(dp6, dp3, dp6, dp3);
        setTextColor(Color.WHITE);
        setTextSize(TypedValue.COMPLEX_UNIT_SP, 11);
        setLines(1);
        setEllipsize(TextUtils.TruncateAt.END);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        canvas.save();

        mRecF.left = 0;
        mRecF.top = 0;
        mRecF.right = getMeasuredWidth();
        mRecF.bottom = getMeasuredHeight();

        canvas.drawRoundRect(mRecF, mTagRadius, mTagRadius, mPaint);

        canvas.restore();
        super.onDraw(canvas);
    }

    public void setTagColor(int tagColor) {
        this.mTagColor = tagColor;

        postInvalidate();
    }

    public void setTagColor(String tagColor) {
        this.mTagColor = StringUtils.isColor(tagColor) ? Color.parseColor(tagColor) : DEFAULT_COLOR;

        mPaint.setColor(mTagColor);
    }
}
